import EchartsWrap from '@/components/widgets/EchartsWrap';
import React, { useEffect, useState } from 'react';
import echarts from 'echarts';
// import styles from './index.less';
import { Select, Radio } from 'antd';
// import { getBridgeProgress, getPedestalTotal } from '@/services/kanbanServices';
import { useSelector } from 'umi';
// import NoData from '../noData';
import moment from 'moment';

const { Option } = Select;

const fontColor = 'rgba(255,255,255, 0.7)';
const option2 = {
  backgroundColor: 'transparent',
  grid: {
    left: '0',
    right: '0',
    top: '20%',
    bottom: '8%',
    containLabel: true,
  },
  tooltip: {
    show: true,
    trigger: 'axis',
  },
  legend: {
    show: true,
    orient: 'horizontal',
    left: 0,
    icon: 'circle',
    itemWidth: 6,
    itemHeight: 6,
    textStyle: {
      color: 'rgba(255,255,255,0.6)',
    },
    data: ['计划', '实际', '计量', '每日产值'],
  },
  xAxis: [
    {
      type: 'category',
      axisLabel: {
        color: fontColor,
        fontSize: 12,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255,255,255,.2)',
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: false,
      },
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
  ],
  yAxis: [
    {
      type: 'value',
      name: '',
      min: 0,
      // max: 1000,
      axisLabel: {
        formatter: '{value}',
        textStyle: {
          color: 'rgba(255,255,255, 0.7)',
        },
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,.2)',
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255,255,255, 0.1)',
          type: 'dashed',
        },
      },
    },
    {
      type: 'value',
      name: '',
      min: 0,
      // max: 1000,
      axisLabel: {
        formatter: '{value}',
        textStyle: {
          color: 'rgba(255,255,255, 0.7)',
        },
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,.2)',
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255,255,255, 0.1)',
          type: 'dashed',
        },
      },
    },
  ],
  series: [
    {
      name: '计划',
      type: 'line',
      smooth: true,
      showSymbol: false,
      itemStyle: {
        normal: {
          color: '#2FB0FF',
          lineStyle: {
            color: '#2FB0FF',
            width: 1,
          },
        },
      },
      data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
    },
    {
      name: '实际',
      type: 'line',
      smooth: true,
      showSymbol: false,
      itemStyle: {
        normal: {
          color: '#FFCE3D',
          lineStyle: {
            color: '#FFCE3D',
            width: 1,
          },
        },
      },
      data: [220, 182, 191, 234, 290, 330, 310, 201, 154, 190, 330, 410],
    },
    {
      name: '每日产值',
      type: 'bar',
      barMaxWidth: 12,
      barMinWidth: 6,
      itemStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(61, 255, 185, 0.45)' },
            { offset: 1, color: 'rgba(61, 255, 185, 0.08)' },
          ]),
        },
      },
      yAxisIndex: 1,
      data: [220, 182, 191, 234, 290, 330, 310, 201, 154, 190, 330, 410],
    },
  ],
};

const TIME_OPTIONS = [
  { value: 'day', label: '天' },
  { value: 'week', label: '周' },
  { value: 'month', label: '月' },
];

function fixDataTo30(data, type = 'day') {
  try {
    if (data.length < 30) {
      let preData = [];
      const createTimeMoment = moment(data[0].createTime);
      for (let index = 0; index < 30 - data.length; index++) {
        preData.unshift({
          ...data[0],
          createTime: createTimeMoment.add(-1, type).format('YYYY-MM-DD hh:mm:ss'),
          totalPlanProductValue: 0,
          totalActualProductValue: 0,
          // calcCurDayPlanProductValue: 0,
          calcCurDayActualProductValue: 0,
        });
      }
      data = [...preData, ...data];
    }
    return data.slice(-30);
  } catch (error) {
    console.warn('换算30天数据失败,请检查数据源', error);
    return [];
  }
}

function getCalcCurData(data) {
  for (let i = 1; i < data.length; i++) {
    // data[i].calcCurDayPlanProductValue = (
    //   data[i].totalPlanProductValue - data[i - 1].totalPlanProductValue
    // ).toFixed(2);
    data[i].calcCurDayActualProductValue = (
      data[i].totalActualProductValue - data[i - 1].totalActualProductValue
    ).toFixed(2);

    if (data[i].calcCurDayActualProductValue < 0) {
      data[i].calcCurDayActualProductValue = 0;
    }
  }
  return data.slice(1);
}

const Statistics = ({ location }) => {
  const [secondChartData, setSecondChartData] = useState(option2);
  const sectionProgress = useSelector(store => store.projectPage.sectionProgress);
  const totalProgress = useSelector(store => store.projectPage.totalProgress);

  const [sectionIndex, setSectionIndex] = useState('total');

  const [timeSelected, setTimeSelected] = useState(TIME_OPTIONS[0].value);
  const [curProduceValue, setCurProduceValue] = useState(0);

  useEffect(() => {
    if (!sectionProgress.length || !totalProgress.length) {
      return;
    }
    console.log(totalProgress, '229');
    //! 假设当前数据是每天连续的前提下
    let data = totalProgress;
    setCurProduceValue(+totalProgress[totalProgress.length - 1].calculateProduceValue / 10000 || 0);
    if ('total' !== sectionIndex) {
      data = sectionProgress[sectionIndex].items;
    }

    let _data = [];
    // 获取过去30天数据
    if (timeSelected === 'day') {
      data = fixDataTo30(getCalcCurData(data.slice(-31)));
    } else if (timeSelected === 'week') {
      // 每个星期产值
      for (let i = 0; i < data.length; i += 7) {
        data[i] && _data.push(data[i]);
      }
      // data = _data.slice(-31);
      data = fixDataTo30(getCalcCurData(_data.slice(-31)), 'week');
    } else {
      // 每个月产值
      //! 暂时搞成三十，但愿起始不是一号 二号
      for (let i = 0; i < data.length; i += 30) {
        data[i] && _data.push(data[i]);
      }
      data = fixDataTo30(getCalcCurData(_data.slice(-31)), 'month');
    }
    // console.log(data,'30份数据')
    if (!data.length) {
      return;
    }
    getNewOption(data, timeSelected);
  }, [sectionIndex, timeSelected, sectionProgress, totalProgress]);

  function getNewOption(data, timeSelected) {
    const newOption = JSON.parse(JSON.stringify(option2));
    const startIndex = timeSelected === 'day' ? 8 : 5;
    const endIndex = timeSelected === 'month' ? 7 : 10;
    // newOption.xAxis[0].nameRotate = timeSelected === 'day' ? 0 : 15;
    // newOption.xAxis[0].axisLabel.rotate = 55;
    const [xAxisArr, planArr, actualArr, productValueArr] = data.reduce(
      (r, item) => {
        const {
          createTime,
          totalPlanProductValue,
          totalActualProductValue,
          calcCurDayActualProductValue,
          // calcCurDayPlanProductValue,
        } = item;
        r[0].push(
          timeSelected === 'week'
            ? moment(createTime).isoWeek()
            : createTime.slice(startIndex, endIndex),
        ); //截取月份和天数   "createTime": "2021-04-26 08:41:54",
        r[1].push({ value: totalPlanProductValue || 0, title: 'createTime' });
        // r[1].push(totalPlanProductValue || 0);
        r[2].push(totalActualProductValue || 0);
        // r[3].push(calcCurDayPlanProductValue || 0);
        r[3].push(calcCurDayActualProductValue || 0);
        return r;
      },
      [[], [], [], [], []],
    );
    newOption.xAxis[0].data = xAxisArr;
    newOption.series[0].data = planArr;
    newOption.series[1].data = actualArr;
    newOption.series[2].data = productValueArr;
    // newOption.series[2].data = calcArr;
    // console.log([xAxisArr, planArr, actualArr, calcArr, productValueArr]);
    setSecondChartData(newOption);
  }

  function handleSlectSection(e) {
    setSectionIndex(e);
  }

  return (
    <div
      style={
        location == 'right'
          ? {
              position: 'absolute',
              right: 0,
              bottom: 0,
              zIndex: 10,
              width: 'calc(100vw - 942px)',
            }
          : {
              position: 'absolute',
              left: 24,
              bottom: 25,
              zIndex: 10,
              width: 'calc(100vw - 942px)',
            }
      }
    >
      <div
        className="base-panel"
        // style={{ }}
      >
        <div className="base-panel-title side-panel2-title" style={{ paddingLeft: 48 }}>
          <span style={{ marginRight: 10 }}>产值统计</span>
          <Select
            // size={'small'}
            defaultValue="total"
            // style={{ width: 160 }}
            onChange={handleSlectSection}
            dropdownClassName="width-400-important"
          >
            <Option value="total">总体</Option>
            {!!sectionProgress.length &&
              sectionProgress.map(({ title }, i) => {
                return (
                  <Option key={title} value={i}>
                    {title}
                  </Option>
                );
              })}
          </Select>
          <span style={{ float: 'right', marginRight: 16, fontSize: 12, opacity: 0.8 }}>
            总计量值：{curProduceValue.toFixed(2)} 亿
          </span>
        </div>
        <div
          className="base-panel-body"
          style={
            location == 'right'
              ? {
                  height: '252px',
                }
              : {
                  height: '240px',
                }
          }
        >
          <div style={{ padding: 16, position: 'relative' }}>
            <Radio.Group
              style={{ position: 'absolute', top: 16, right: 16, zIndex: 10 }}
              options={TIME_OPTIONS}
              onChange={e => {
                setTimeSelected(e.target.value);
              }}
              value={timeSelected}
              optionType="button"
              buttonStyle="solid"
            />
            <EchartsWrap option={secondChartData} style={{ height: 220 }} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Statistics;
